#include <FreeRTOS.h>
#include "bflb_gpio.h"
#include "queue.h"
#include "task.h"
#include "usbh_core.h"
#include "bflb_mtimer.h"
#include "board.h"
#include "matrix.h"

#include "usbd_hid.h"

#define KEYBOARD_STACK_SIZE (1536)
#define KEYBOARD_TASK_PRIORITY (16)

extern void hid_keyboard_init(void);
extern void hid_keyboard_test(void);
extern void hid_send_key(uint16_t val);
uint16_t char2USBkey(char key);

static TaskHandle_t keyboard_task_hd, matrix_key_task_hd;
QueueHandle_t xQueue;

void matrix_keys_task(void *params)
{
    uint16_t key_val = 0;
    char key_char;
    matrix_keys_init();
    while(1)
    {
		key_val = get_key_val();
        key_char = val2char(key_val);
        key_val = char2USBkey(key_char);
        if (xQueueSend(xQueue, &key_val, portMAX_DELAY) != pdPASS) 
        {
        }
        bflb_mtimer_delay_ms(100);
    }
}


void keyboard_task(void *params)
{
    hid_keyboard_init();
    uint16_t receivedData = 0;
    while(1)
    {
        if (xQueueReceive(xQueue, &receivedData, portMAX_DELAY) == pdPASS) 
        {
            printf("receivedData : %x\r\n", receivedData);
            // 处理接收到的数据
            hid_send_key(receivedData);
		}
        bflb_mtimer_delay_ms(100);
    }
}


int main(void)
{
    board_init();
    xQueue = xQueueCreate(10, sizeof(uint16_t));
    xTaskCreate(keyboard_task, "keyboard", 
        KEYBOARD_STACK_SIZE, NULL, KEYBOARD_TASK_PRIORITY, &keyboard_task_hd);

    xTaskCreate(matrix_keys_task, "matrix_keys", 
        KEYBOARD_STACK_SIZE, NULL, KEYBOARD_TASK_PRIORITY, &matrix_key_task_hd);

    vTaskStartScheduler();
    while (1) {
    }
}

uint16_t char2USBkey(char key)
{
    uint16_t keyval = 0;
    switch (key)
    {
        case '1':
            keyval = HID_KBD_USAGE_EXCLAM;
            break;
        case '2':
            keyval = HID_KBD_USAGE_AT;
            break;
        case '3':
            keyval = HID_KBD_USAGE_POUND;
            break;
        case 'A':
            keyval = HID_KBD_USAGE_A;
            break;
        case '4':
            keyval = HID_KBD_USAGE_DOLLAR;
            break;
        case '5':
            keyval = HID_KBD_USAGE_PERCENT;
            break;
        case '6':
            keyval = HID_KBD_USAGE_CARAT;
            break;
        case 'B':
            keyval = HID_KBD_USAGE_A + 1;
            break;
        case '7':
            keyval = HID_KBD_USAGE_AMPERSAND;
            break;
        case '8':
            keyval = HID_KBD_USAGE_ASTERISK;
            break;
        case '9':
            keyval = HID_KBD_USAGE_LPAREN;
            break;
        case 'C':
            keyval = HID_KBD_USAGE_A + 2;
            break;
        case '*':
            keyval = HID_KBD_USAGE_KPDMUL;
            break;
        case '0':
            keyval = HID_KBD_USAGE_0;
            break;
        case '#':
            keyval = HID_KBD_USAGE_KPDPOUND;
            break;
        case 'D':
            keyval = HID_KBD_USAGE_A + 3;
            break;
    }
    return keyval;
}


